# coding=UTF-8
from google.appengine.ext.db import djangoforms as forms
from google.appengine.ext import db
from models import Post, Comment
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.list_detail import object_list
from google.appengine.api import users
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.core.paginator import Paginator, InvalidPage
from django.views.decorators.vary import vary_on_headers
from django.views.decorators.cache import cache_control
from django.views.decorators.cache import cache_page
from django.utils.encoding import force_unicode,smart_str

import datetime
import authorized
import urllib


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ['author','permalink','tags', 'lastCommentedDate', 'commentcount', 'lastModifiedDate', 'lastModifiedBy', ]

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['post', 'date', 'author', 'userIp', 'lastModifiedDate', 'lastModifiedBy', ]

@authorized.role("user")
def add_post(request):
    user=users.get_current_user()
    if request.method == 'GET':
        form = PostForm({'authorEmail':str(user.email()),'catalog':'未分类', })
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.author = user
            post.save()
            return HttpResponseRedirect('/')
    
    template_values={'form': form, 'user':user, }
    return render_to_response('blog/add_post.html', template_values,)

@cache_control(must_revalidate=True, max_age=60*3)#cache_control 告诉缓存对每次访问都重新验证缓存并在最长 3600 秒内保存所缓存版本
@vary_on_headers('User-Agent','Cookie')
def view_post(request, id):
    postId_ = int(id)
    post= Post.get_by_id(postId_)
    comments = db.GqlQuery("select * from Comment where post = :1  order by date", post)
    if post:
        user = users.get_current_user()
        if request.method == 'GET':
            if user:
                form = CommentForm({'user':str(user.nickname()), 'authorEmail':str(user.email()), })
            else:
                form = CommentForm()
       
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                comment = form.save()
                comment.post = post
                comment.userIp = request.META['REMOTE_ADDR']
                if user:
                    comment.author = user
                    comment.authorEmail = str(user.email())
                    comment.user = str(user.nickname())
                comment.save()
                return HttpResponseRedirect('/post/'+id)
                
        template_values = {
                  'user' : user,
                  'post' : post,
                  'comments': comments,
                  'form' : form,
        }
        return render_to_response('blog/view_post.html', template_values,)
    else:
        return HttpResponseForbidden()
    
@authorized.role("user")
def edit_post(request, id):
    user=users.get_current_user()
    post=Post.get_by_id(int(id))
    if post:
        if post.author==users.get_current_user():
            if request.method == 'POST':
                form = PostForm(request.POST)
                if form.is_valid():
                    post.title=form.cleaned_data.get('title', '')
                    post.content=form.cleaned_data.get('content', '')
                    post.authorEmail=form.cleaned_data.get('authorEmail', '')
                    post.catalog=form.cleaned_data.get('catalog', '')
                    post.lastModifiedBy=user
                    post.lastModifiedDate=datetime.datetime.now()
                    post.save()
                    return HttpResponseRedirect('/')
            else:
                data={
                      'title':post.title,
                      'content':post.content,
                      'authorEmail':post.authorEmail,
                      'catalog':post.catalog,
                      }
                form=PostForm(data)
            template_values={'form': form, 'user':user, }
            return render_to_response('blog/add_post.html', template_values,)
    
    return HttpResponseForbidden()
    
@authorized.role("user")
def delete_post(request, id):
    post=Post.get_by_id(int(id))
    if post:
        if post.author==users.get_current_user():
            post.delete()
            return HttpResponseRedirect('/')
    return HttpResponseForbidden()

def logout(request):
    return HttpResponseRedirect(users.create_logout_url("/"))

def login(request):
    return HttpResponseRedirect(users.create_login_url("/1"))

@cache_control(must_revalidate=True, max_age=60*3)#cache_control 告诉缓存对每次访问都重新验证缓存并在最长 3600 秒内保存所缓存版本
@vary_on_headers('User-Agent','Cookie')
def list_post(request, page=1):
    page =int(page)
    postsPage=Paginator(Post.all().order('-date'), 5, orphans=3)
    page1=postsPage.page(page)
    dict = {'posts':page1.object_list,
            'pageCount':postsPage.num_pages,
            'postCount':postsPage.count,
            'currentPage':page,
            'has_previous': page1.has_previous(),
            'previous_page': page1.previous_page_number(),
            'has_next':page1.has_next(),
            'next_page':page1.next_page_number(),
            'user':users.get_current_user(),
    }
    return render_to_response('blog/list_post.html', dict)

@cache_control(must_revalidate=True, max_age=3600)
@vary_on_headers('User-Agent','Cookie')
def catalog(request,catalog,page=1):
    page =int(page)
    catalog = force_unicode(urllib.unquote(smart_str(catalog))) 
    postsPage=Paginator(Post.all().filter("catalog =", catalog).order('-date'), 5, orphans=3)
    page1=postsPage.page(page)
    dict = {'posts':page1.object_list,
            'pageCount':postsPage.num_pages,
            'postCount':postsPage.count,
            'currentPage':page,
            'has_previous': page1.has_previous(),
            'previous_page': page1.previous_page_number(),
            'has_next':page1.has_next(),
            'next_page':page1.next_page_number(),
            'user':users.get_current_user(),
    }
    return render_to_response('blog/list_post.html', dict)